//
//  YDFreeAdvertViewController.m
//  PeiZiWangBei
//
//  Created by 巨彦新 on 2018/1/8.
//  Copyright © 2018年 LK-IOS. All rights reserved.
//

#import "YDFreeAdvertViewController.h"
#import "YDBuyStrategyTopView.h"
#import "YDRechargeWithdrawalButtonView.h"
#import "YDPayAlertView.h"
#import "YDOneRechargeViewController.h"
#import "YDRechargeController.h"
#import "YDStrategyTypeModel.h"
#import "YDLossRateModel.h"
#import "YDPaymentPasswordController.h"
#import "YDQuestionController.h"

@interface YDFreeAdvertViewController ()<SYRechargeWithdrawalButtonViewDelegate>
//显示单只股票信息的view
@property (nonatomic , weak) YDBuyStrategyTopView *topView;
//当前股票的最新信息
@property (nonatomic, copy)NSDictionary *currentStock;

@property (nonatomic , weak) YDRechargeWithdrawalButtonView *buttonView;

@property (weak, nonatomic) IBOutlet UIView *bgview;
@property (weak, nonatomic) IBOutlet UILabel *buyStockLbl;
@property (weak, nonatomic) IBOutlet UILabel *shouLbl;

@property (nonatomic, strong)YDStrategyTypeModel *strategyModel; //免费策略数据model

@end

@implementation YDFreeAdvertViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"免费发布策略";
    [self getStockNewMarket];
    [self loadStrategyData];
    [self setNav];

}
- (void)setNav
{
    UIBarButtonItem *rightItemBtn = [UIBarButtonItem imageWithNormalImage:[UIImage imageNamed:@"h-guize"] hightImage:[UIImage imageNamed:@"h-guize"] addTarget:self action:@selector(rightItemBtnClick:)];
    self.navigationItem.rightBarButtonItem = rightItemBtn;
}
-(void)rightItemBtnClick:(UIButton *)button
{
    //    DDLog(@"点击股票搜索界面的编问好")
    YDQuestionController *vc = [[YDQuestionController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 请求策略数据
- (void)loadStrategyData
{
    
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:Get2000FreeStrategy WithSuccessBlock:^(NSDictionary *resultDict) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        if ([resultDict[@"code"] integerValue] == 200)
        {
            self.strategyModel = [YDStrategyTypeModel mj_objectWithKeyValues:resultDict[@"result"]];
            
        }
        else
        {
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                            WithType:NavTipsViewTypeMessage text:resultDict[@"message"]
                                                          isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage text:@"网络异常"
                                                      isExistNav:YES];
    }];
}

//加载单只股票信息
-(void)getStockNewMarket
{
    [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
    NSString *url = [NSString stringWithFormat:@"%@%@",@"/stock/market/" , self.stockCode];
    NSString *baseUrl = [NSString stringWithFormat:@"%@%@",baseUrlHttp , url];
    NSString *authToken = [[SYUserDataManger sharedInstance] getUserToken];
    BaseNetRequest *request = [[BaseNetRequest alloc] initWithRequestMethod:GETMethod];
    [request sessionRequestWithDictionary:nil andURLString:baseUrl andAuthToken:authToken WithSuccessBlock:^(NSDictionary *resultDict) {
         [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        DDLog(@"resultDict = %@" , resultDict)
        if ([resultDict[@"code"] integerValue] == 200) {
         self.currentStock = resultDict[@"result"];
            if ([resultDict[@"result"][@"status"] integerValue] == 1) {
                //非停牌股票才显示T+1
              //  [self setTitleView];
                [self addChildView];
                
            }else{
                [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
                [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"改股票现已停牌，请留意实时信息" isExistNav:YES];
                
            }
            
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                            WithType:NavTipsViewTypeMessage text:resultDict[@"message"]
                                                          isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage text:@"网络异常"
                                                      isExistNav:YES];
    }];
}

- (void)addChildView
{
    [self topView];
    [self buttonView];
    self.bgview.hidden = NO;
    [self.bgview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_topView.mas_bottom).offset(10);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(_buttonView.mas_top);
    }];
    [self setStockLbls];
}

- (void)setStockLbls
{
    NSString *stockName = [self.currentStock objectForKey:@"name"];
    
    NSString *str = [NSString stringWithFormat:@"可购买%@股票",stockName];
    NSRange subRange = [str rangeOfString:stockName];
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:str];
    
    [attri addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:Orange] range:subRange];
    
    self.buyStockLbl.attributedText = attri;
    NSNumber *price = [self.currentStock objectForKey:@"lastPrice"];
    
    if ([price intValue] == 0) {
        self.shouLbl.text = @"0手";
    }else
    {
        self.shouLbl.text = [NSString stringWithFormat:@"%d手",(int)(20/price.doubleValue)];
    }
    
    
    
}
#pragma mark - 获取设置支付密码信息
-(void)loadUserCardBindInfo
{
    
    [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
    
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetSettingInformationList WithSuccessBlock:^(NSDictionary *resultDict) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        
        if ([resultDict[@"code"] integerValue] == 200) {
            
            BOOL isBindCard = [resultDict[@"result"][@"settingPaymentPassword"] boolValue];
            
            if (!isBindCard) {
                
                [self goSetupPayPassword];
            }
            else
            {
                [self pay];
            }
            
        }else{
            
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"信息加载出错，请重试~" isExistNav:YES];
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failBlock:^(NSError *error) {
        
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"信息加载出错，请重试~" isExistNav:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}
#pragma SYRechargeWithdrawalButtonViewDelegate

-(void)rechargeWithdrawalButtonViewButtonClick
{
    if ([[self.currentStock objectForKey:@"upLimitPrice"] floatValue] > 20) {
        [self Higher20yuan];
        return;
    }
    
    if(![NSDate stockTradingTimeJudgment])
    {
        [self noTransactionTimeAlert];
        return;
    }
    
    [self loadUserCardBindInfo];
}

- (void)pay
{
    if (self.strategyModel != nil) {
        //免费策略 写死
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        YDLossRateModel *lose = [self.strategyModel.losses firstObject];
        
        
        [dict setObject:@(self.strategyModel.Id) forKey:@"strategyTypeId"];//策略类型ID
        [dict setObject:@2000 forKey:@"applyAmount"];//申请是市值
        
        [dict setObject:@0 forKey:@"serviceFee"];//服务费
        [dict setObject:@100 forKey:@"reserveFund"];//保证金
        [dict setObject:@(0.5) forKey:@"profitPoint"];//止盈点
        [dict setObject:@(-[lose.point floatValue]) forKey:@"lossPoint"];//止损点
        [dict setObject:self.stockCode forKey:@"stockCode"];//股票代码
        [dict setObject:@0 forKey:@"deferred"];//是否递延
        
        [dict setObject:[self.currentStock objectForKey:@"upLimitPrice"] forKey:@"delegatePrice"];//股票涨停价格
        DDLog(@"dict = %@" , dict)
        
        
        YDPayAlertView *payView = [[YDPayAlertView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, LKScreenH) inputFinish:^(NSString *passWord) {
            
            [dict setObject:passWord forKey:@"paymentPassword"];
            [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
            [BaseNetRequest sessionRequestWithparameters:dict
                                                       method:POSTMethod
                                                   requstType:BuyStock
                                             WithSuccessBlock:^(NSDictionary *resultDict) {
                                                 [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
                                                 if ([resultDict[@"code"] integerValue] == 200)
                                                 {
                                                     
                                                     [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                                                                     WithType:NavTipsViewTypeMessage text:@"购买成功"
                                                                                                   isExistNav:YES];
                                                     
                                                     
                                                     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                                         
                                                         [self.navigationController popToRootViewControllerAnimated:NO];
                                                         
                                                         dispatch_async(dispatch_get_main_queue(), ^{
                                                             [[NSNotificationCenter defaultCenter] postNotificationName:kBuySuccessNoti object:nil];
                                                         });
                                                         
                                                     });
                                                     
                                                     
                                                     
                                                 }
                                                 else if ([resultDict[@"code"] integerValue] == 6001)
                                                 {
                                                     //账号余额不足
                                                     [self showAccountBalanceNotEnoughAlert];
                                                     
                                                 }
                                                 else if ([resultDict[@"code"] integerValue] == 6013)
                                                 {
                                                     //非交易时间段
                                                     [self noTransactionTimeAlert];
                                                 }
                                                 else
                                                 {
                                                     
                                                     [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                                                                     WithType:NavTipsViewTypeMessage text:resultDict[@"message"]
                                                                                                   isExistNav:YES];
                                                 }
                                                 
                                             } failBlock:^(NSError *error) {
                                                 [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
                                                 
                                                 if ([ErrorMessageManager showErrorMessageWithError:error vc:self]) {
                                                     
                                                 }
                                                 else
                                                 {
                                                     [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                                                                     WithType:NavTipsViewTypeMessage
                                                                                                         text:@"信息加载出错！"
                                                                                                   isExistNav:YES];
                                                 }
                                             }];
        }];
        [payView show];
    }
 
}

- (void)showAccountBalanceNotEnoughAlert
{
    //账户余额不足提示
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:@"账户余额不足，请先充值！" ButtonTitle:@"去充值" ButtonClickBlock:^{
        
        [self.navigationController pushViewController:[[YDRechargeController alloc] init] animated:YES];
        
        [self.pz_popupController dismiss];
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}



- (void)noTransactionTimeAlert
{
    //非交易时间段弹窗
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:@"现在是非交易时间段，请在交易时间内点买。\n交易时间段：（国家法定节假日除外）周一至周五\n09:30-11:30 13:00-14:50" ButtonTitle:@"我知道了" ButtonClickBlock:^{
        
        
        [self.pz_popupController dismiss];
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}

- (void)Higher20yuan
{
    //大于20块弹窗
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:@"您选择的股票市值高于2000，请选择其他股票" ButtonTitle:@"我知道了" ButtonClickBlock:^{
        
        
        [self.pz_popupController dismiss];
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}
-(void)goSetupPayPassword
{
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:@"您还没有设置支付密码，请先设置支付密码" ButtonTitle:@"去设置" ButtonClickBlock:^{
        
        
        [self.pz_popupController dismiss];
        YDPaymentPasswordController *vc = [[YDPaymentPasswordController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}


//顶部显示单只股票的view
-(YDBuyStrategyTopView *)topView
{
    if (_topView == nil) {
        YDBuyStrategyTopView *topView = [YDBuyStrategyTopView buyStrategyTopViewWithStockDict:self.currentStock];
        [self.view addSubview:topView];
        [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self.view);
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(74)));
            }else{
                make.height.equalTo(@(rate750(74)));
            }
            
        }];
        _topView = topView;
    }
    return _topView;
}

#pragma YDRechargeWithdrawalButtonView
/////********立即买入按钮*******///////
-(YDRechargeWithdrawalButtonView *)buttonView
{
    if (_buttonView == nil) {
        YDRechargeWithdrawalButtonView *buttonView = [YDRechargeWithdrawalButtonView rechargeWithdrawalButtonWithButtonTitle:@"立即发布"];
        [self.view addSubview:buttonView];
        
        [buttonView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(63)));
            }else{
                make.height.equalTo(@(rate750(50)));
            }
        }];
        buttonView.delegate = self;
        [buttonView enableButton];
        _buttonView = buttonView;
    }
    return _buttonView;
}


@end
